import React, {Component} from 'react';
import {Input, Row, Col, Form, Button, Select, Option, Modal} from 'antd';
import {connect} from 'dva';

const FormItem = Form.Item;
import shouldComponentUpdate from '../../components/decorator/shouldComponentUpdate';

const styles = {
  contentBox: {
    background: '#fff'
  }
};

@shouldComponentUpdate
class ScanQrcode extends Component {
  constructor(props, context) {
    super(props, context);
  }
  state = {
    focusIndex: 0,
    size: 20
  }
  handleSubmit = (e) => {
    e.preventDefault();
    const {form,history,dispatch} = this.props;
    Array.prototype.notempty = function () {
      var arr = [];
      this.map(function (val, index) {
        if (val !== "" && val != undefined) {
          arr.push(val);
        }
      });
      return arr;
    }
    form.validateFields((err, values) => {
      if (!err) {
        let finalArr = (Object.values(values)).notempty()
        console.log('Received values of form: ', finalArr);
        if(!finalArr.length) {
          Modal.error({
            title: 'error',
            content: '请先扫描录入二维码',
          });
          return
        }
        localStorage.setItem('qrcodeList',JSON.stringify(finalArr))
        dispatch({
          type: 'testDevice/querySuccess',
          payload: {
            testType: 1
          },
        });
        history.push("/testDevice");
      }
    });
  }
  handleChange = (key,e) => {
    // 扫描录入后 只截取':'后的的字符
    const {form} = this.props;
    const {getFieldsValue, setFieldsValue} = form;
    const fields = getFieldsValue();
    let oEvent = e || window.event;
    let values = oEvent.target.value;
    let oValue = values&&values.indexOf('IMEI:') > -1 ? values.split("IMEI:")[1] : values;
    for(let k in fields) {
      if(oValue && fields[k] === oValue && k !== key) {
        Modal.error({
          title: 'error',
          content: '不能重复录入二维码',
        });
        oValue = ''
        break
      }
    }

    fields[key] = oValue;
    setFieldsValue(fields);
    oEvent.target.value = oValue;
    if(oValue&&this.state.focusIndex<19&&(new RegExp(/^[A-Za-z0-9]+$/).test(oValue))&&oValue.length>=15) {
      let oInput = document.querySelector(`#qrcode${this.state.focusIndex+1}`)
      oInput.focus()
    }
  }
  inputFocus = (oIndex) => {
    this.setState({
      focusIndex: oIndex
    })
  }
  componentDidMount() {
    let oInput = document.querySelector('#qrcode0')
    oInput.focus()
  }

  render() {
    const {form, scanQrcode: {canTest}} = this.props;
    const {getFieldDecorator} = form;
    let oArr = Array.from(new Array(20).keys());
    return (
      <Form className="content-inner">
        <Row gutter={16}>
          {
            oArr.map((item, i) => <Col span={6}><FormItem label="二维码信息" hasFeedback>
              {getFieldDecorator(`qrcode${i}`, {
                initialValue: '',
                rules: [
                  {pattern: /^[A-Za-z0-9]+$/,message: '请输入正确格式，例：IMEI:123'}
                ]
              })(<Input placeholder='请扫描录入二维码信息' onChange={this.handleChange.bind(null,`qrcode${i}`)} onFocus={this.inputFocus.bind(null,i)}/>)}
            </FormItem></Col>)
          }
          <Col span={24}>
            <FormItem
              wrapperCol={{offset: 22}}>
              <Button type="primary" disabled={!canTest} onClick={this.handleSubmit}>
                进行测试
              </Button>
            </FormItem>
          </Col>
        </Row>
      </Form>
    );
  }
}

const Detail = Form.create()(ScanQrcode);

ScanQrcode.propTypes = {};

export default connect(({scanQrcode}) => ({scanQrcode}))(Detail);

